package com.aplink.generic.fragments;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

import com.aplink.generic.GenericFragment;
import com.aplink.generic.adapter.LanguageAdapter;
import com.aplink.generic.cache.ContentDataManager;
import com.aplink.generic.database.DatabaseHelper;
import com.aplink.generic.pojo.ContentData;
import com.aplink.generic.sharepreference.GenericSharePreference;
import com.aplink.sg.R;

public class LanguageDialogFragment extends DialogFragment {
	public static LanguageDialogFragment newInstance(
	        GenericFragment genericFragment) {
		return new LanguageDialogFragment(genericFragment);
	}

	private ContentData contentData;

	GenericFragment mGenericFragment;

	private LanguageAdapter mLanguageAdapter;

	private DialogInterface.OnClickListener onLanguageItemClick = new OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			AlertDialog alertDialog = (AlertDialog) dialog;
			int position = alertDialog.getListView().getCheckedItemPosition();
			String languageID = ((LanguageAdapter) (alertDialog.getListView()
			        .getAdapter())).getLanguageID(position);
			String languageCode = ((LanguageAdapter) (alertDialog.getListView()
			        .getAdapter())).getLanguageCode(position);
			GenericSharePreference.getInstance().setCurrentLanguage(languageID,
			        languageCode);
			GenericSharePreference.getInstance().setLanguageChanged(true);
			dismiss();
		}
	};

	private LanguageDialogFragment(GenericFragment genericFragment) {
		mGenericFragment = genericFragment;
		contentData = ContentDataManager.getInstance().get(
		        R.raw.contentdata_language);
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		mLanguageAdapter = new LanguageAdapter(getActivity(), DatabaseHelper
		        .getInstance().getList(contentData, null));
		int index = mLanguageAdapter.getPosition(GenericSharePreference
		        .getInstance().getCurrentLanguage());
		builder.setSingleChoiceItems(mLanguageAdapter, index,
		        onLanguageItemClick);
		builder.setTitle("Language Settings");
		return builder.create();
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		super.onDismiss(dialog);
		mGenericFragment.languageChanged();
	}
}
